package com.wisemoresystem.seal.action.location;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.base.tip.Tip;
import com.wisemoresystem.seal.config.Config;
import com.wisemoresystem.seal.config.FileFolderTools;
import com.wisemoresystem.seal.model.t_file;
import com.wisemoresystem.seal.model.t_location;
import com.wisemoresystem.seal.service.LocationService;
import com.wisemoresystem.seal.util.ExcelReadToolForList;
import com.wisemoresystem.seal.util.doc.excel.ExcelExport;
import com.wisemoresystem.seal.util.doc.excel.ExcelReadTools;
import com.wisemoresystem.seal.util.json.JsonTools;
import com.wisemoresystem.seal.web.WebTools;

/**
 * 区域管理
 * 
 * @author Administrator
 *
 */
@Controller("ixLocation")
@Scope("prototype")
@RequestMapping("/ix/location")
public class LocationAction extends ProjBaseAction {

	public static List<Map<String, Object>> list;
	public static String locationJson;
	@Autowired
	private LocationService lService;

	/**
	 * 区域列表
	 * 
	 * @param location_id
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(String location_id) {

		if (list == null) {
			list = lService.selectLocation();
			locationJson = JsonTools.toJson(list);
		}

		ModelAndView mv = new ModelAndView("/jsp/location/tree");
		mv.addObject("locationJson", locationJson);
		mv.addObject("location_id", location_id);
		return mv;
	}

	/**
	 * 异步加载区域
	 * 
	 * @param location_id
	 * @throws IOException
	 */
	@RequestMapping("/async_list")
	public void async_list(String location_id) throws IOException {
		resp.setCharacterEncoding("utf-8");

		List<Map<String, Object>> list = lService
				.selectLocationByAsync(location_id);

		String locationJson = JsonTools.toJson(list);

		resp.getWriter().print(locationJson);
		resp.getWriter().flush();
	}

	/**
	 * 通过code查找区域
	 * 
	 * @param code
	 */
	@RequestMapping("/get_location")
	@ResponseBody
	public String get_location(String code) throws IOException {

		t_location location = lService.selectLocationByCode(code);
		System.out.println(code + "---" + location.getName());
		return location.getName();
	}

	@RequestMapping("/add_form")
	public ModelAndView add_form() {

		ModelAndView mv = new ModelAndView("/jsp/location/add_form");
		return mv;
	}

	/**
	 * 添加区域
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(t_location location) {

		location.setUser_id(WebTools.getCurrentUserId());
		if (ChkTools.isNull(location.getSuper_id())) {
			location.setSuper_id("root");
		}
		oc.saveObj(location);

		logT.logH("添加区域", t_location.class, location.get_id());

		super.setTipMsg("保存成功！", Tip.Type.success);
		ModelAndView mv = new ModelAndView("redirect:list.htm");
		mv.addObject("location_id", location.getSuper_id());
		return mv;
	}

	@RequestMapping("/edit_form")
	public ModelAndView edit_form(String location_id) {

		t_location tLoc = lService.selectLocationById(location_id);

		ModelAndView mv = new ModelAndView("/jsp/location/edit_form");
		mv.addObject("location", tLoc);
		return mv;
	}

	/**
	 * 修改区域
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(String id, t_location location) {

		t_location tLoc = lService.selectLocationById(id);
		tLoc.setCode(location.getCode());
		tLoc.setName(location.getName());
		oc.updateObj(tLoc);

		logT.logH("修改区域", t_location.class, tLoc.get_id());

		super.setTipMsg("修改成功！", Tip.Type.success);
		ModelAndView mv = new ModelAndView("redirect:list.htm");
		mv.addObject("location_id", id);
		return mv;
	}

	/**
	 * 删除区域
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	public ModelAndView edit(String id) {

		t_location tLoc = lService.selectLocationById(id);
		boolean islive = lService.isLive(id);
		if (islive) {
			super.setTipMsg("删除不成功！存在下级区域！", Tip.Type.warning);
		} else {
			oc.delObj(tLoc);
			super.setTipMsg("删除成功！", Tip.Type.success);
			logT.logH("删除区域", t_location.class, tLoc.get_id());
		}

		ModelAndView mv = new ModelAndView("redirect:list.htm");
		return mv;
	}

	/**
	 * 添加子机构
	 * 
	 * @return
	 */
	@RequestMapping("/add_child")
	public ModelAndView add_child(String id) {

		t_location tLoc = lService.selectLocationById(id);

		ModelAndView mv = new ModelAndView("/jsp/location/add_child");
		mv.addObject("location", tLoc);
		return mv;
	}

	/**
	 * 下载模板
	 * 
	 * @return
	 */
	@RequestMapping("/export_m")
	public ModelAndView exportMo() throws IOException {
		String tit = "中国区域及其编码";

		String[] arrays = { "区域编码", "地区名称", "所属区域编码" };

		ExcelExport<t_location> ts = new ExcelExport<t_location>();
		String filename = System.currentTimeMillis() + ".xls";

		File file = new File(FileFolderTools.getExportFolder(), filename);
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			ts.exportExcelL(tit, "中国区域及其编码", arrays, os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				os.close();
			}
		}
		ModelAndView mv = new ModelAndView("redirect:"
				+ FileFolderTools.getExportUrl() + filename);
		return mv;
	}

	// //工资表
	// @RequestMapping("/export_c")
	// public ModelAndView export(String enterprise_id, String month) throws
	// IOException {
	// String tit = "中国区域及其编码";
	//
	// String[] arrays = {"用工号","账号", "身份证号", "姓名", "应发工资", "养老保险扣款","失业保险扣款",
	// "医疗保险扣款", "大病扣款", "公积金扣款", "其他扣款", "个调税", "扣款合计", "实发工资"};
	//
	// List<Map<String, Object>> list = lService.downloadMonthSalaryList();
	//
	// ExcelExport<t_location> ts = new ExcelExport<t_location>();
	//
	// String filename = System.currentTimeMillis() + ".xls";
	// File file = new File(FileFolderTools.getExportFolder(), filename);
	// if (!file.getParentFile().exists()) {
	// file.mkdirs();
	// }
	// OutputStream os = null;
	// try {
	// os = new FileOutputStream(file);
	// ts.exportExcel(tit,"工资表单", arrays, list, os);
	// os.flush();
	// } catch (IOException e) {
	// e.printStackTrace();
	// } finally {
	// if (os != null) {
	// os.close();
	// }
	// }
	// ModelAndView mv = new ModelAndView("redirect:"
	// + FileFolderTools.getExportUrl() + filename);
	// return mv;
	// }
	/**
	 * 倒入数据
	 * 
	 * @param file_id
	 *            文件id
	 * @throws IOException
	 */
	@RequestMapping("/import_c")
	public void importlinkmans(String file_id) throws IOException {
		resp.setCharacterEncoding("utf-8");

		t_file tf = lService.selectFileById(file_id);
		File file = new File(
				Config.DATA_PATH + File.separator + tf.getFolder(),
				tf.getNew_file_name());
		if (!file.exists()) {
			file = new File(Config.DATA_PATH, "file404.jpg");
		}

		InputStream is = null;
		try {
			is = new FileInputStream(file);
			// 对读取Excel表格标题测试
			ExcelReadTools excelReader = new ExcelReadTools();

			// 对读取Excel表格内容测试
			Map<Integer, String> map = excelReader.readExcelContent(is);
			String par = map.get(1);
			String[] obj = par.split("#");
			String[] content = { "code", "name", "super_code" };
			try {
				List<Map<String, Object>> list = ExcelReadToolForList
						.turnToList(content, map, obj.length);
				System.err.println(list.size() + "===" + list);
				try {
					lService.saveLocation(list);
				} catch (RuntimeException e1) {
					resp.getWriter().print("导入失败！");
					resp.getWriter().flush();
					return;
				}
			} catch (RuntimeException e) {
				resp.getWriter().print("导入文件不符合！");
				resp.getWriter().flush();
				return;
			}

			resp.getWriter().print("导入成功");
			resp.getWriter().flush();
		} catch (FileNotFoundException e) {
			// System.out.println("未找到指定路径的文件!");
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
